<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;


class ClaimProject extends Model
{
    protected  $table='claim_project';

    protected $fillable = [
        'team_name',
        'org_id',
        'logo',
        'name',
        'address',
        'begin',
        'end',
        'cover',
        'banner',
        'publish_time',
        'content',
        'status'
    ];

    protected $casts = [
        'banner' => 'array',
    ];

    public function getBannerAttribute() {
        if (isset($this->attributes['banner'])) {
            try {
                $this->attributes['banner'] = json_decode($this->attributes['banner']);
            }catch (\Exception $e) {

            }

            if (is_array($this->attributes['banner'])) {
                return join(',', $this->attributes['banner']);
            }

            return $this->attributes['banner'];
        }

        return null;
    }

    public function setBannerAttribute($value) {
        if (!empty($value)) {
            $value = explode(',', $value);
            $value = json_encode($value);
        }

        $this->attributes['banner'] = $value;
    }

    public function getBeginAttribute() {
        if (isset($this->attributes['begin'])) {
            $date = new Carbon($this->attributes['begin']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setBeginAttribute($value) {
        $value = strtotime(date('Y-m-d', $value).' 00:00:00');

        $date = new Carbon();
        $date->setTimestamp($value);

        $this->attributes['begin'] = $date->toDateTimeString();
    }

    public function getEndAttribute() {
        if (isset($this->attributes['end'])) {
            $date = new Carbon($this->attributes['end']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setEndAttribute($value) {
        $value = strtotime(date('Y-m-d', $value).' 23:59:59');

        $date = new Carbon();
        $date->setTimestamp($value);
        $this->attributes['end'] = $date->toDateTimeString();
    }

    public function getPublishTimeAttribute() {
        if (isset($this->attributes['publish_time'])) {
            $date = new Carbon($this->attributes['publish_time']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setPublishTimeAttribute($value) {
        if (!isset($value) || empty($value)) {
            return;
        }

        $date = new Carbon();
        $date->setTimestamp($value);

        $this->attributes['publish_time'] = $date->toDateTimeString();
    }

    public function org() {
        return $this->belongsTo('App\Models\Org', 'org_id', 'id');
    }
}
